package com.frog.service.friend.service.api;

import com.frog.service.friend.api.BuildFriendlyRelationshipsApi;
import com.frog.service.friend.enums.FriendTypeEnum;
import com.frog.service.friend.service.relation.Relation;
import com.frog.service.friend.service.factory.RelationFactory;
import com.frog.service.friend.service.message.FriendAddMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * Creted by fjx on 2023/10/26
 */

@Slf4j
@Service
public class FriendRelationshipServiceImpl implements BuildFriendlyRelationshipsApi {


    @Autowired
    private RelationFactory relationFactory;
    @Autowired
    private FriendAddMessageService friendAddMessageService;

    /**
     * 操作好友关系,主要包括用户关注关系、用户拉黑关系、用户bestfriend关系的添加和取消。
     */
    @Override
    public boolean friendRelatedActions(String userIdstr, String friendUserIdstr, FriendTypeEnum friendTypeEnum) {
        if (StringUtils.isBlank(userIdstr) || StringUtils.isBlank(friendUserIdstr) || friendTypeEnum == null)
            return false;
        Integer userId = Integer.parseInt(userIdstr);
        Integer friendUserId = Integer.parseInt(friendUserIdstr);
        // 删除添加好友信息
        if (friendTypeEnum == FriendTypeEnum.deleteAddMessage) {
            return friendAddMessageService.deleteAddMessage(userId, friendUserId);
        }
        Relation serviceInstance = relationFactory.getServiceInstance(friendTypeEnum);
        if (serviceInstance == null) return false;
        switch (friendTypeEnum) {
            case addFollow:
            case addBest:
            case addBlock:
                return serviceInstance.establish(userId, friendUserId);
            case cancelBest:
            case cancelBlock:
                return serviceInstance.termination(userId, friendUserId);
            case cancelFollow:
                return this.cancelMultFollowAndBest(userId, friendUserId);
            default:
                return false;
        }
    }


    /**
     * 取消双向关注关系后,把bestfriend关系也解除掉
     */
    private boolean cancelMultFollowAndBest(Integer userId, Integer friendUserId) {
        Relation serviceInstance = relationFactory.getServiceInstance(FriendTypeEnum.cancelFollow);
        boolean termination = serviceInstance.termination(userId, friendUserId);
        if (termination) {
            Relation serviceInstanceBest = relationFactory.getServiceInstance(FriendTypeEnum.cancelBest);
            serviceInstanceBest.termination(userId, friendUserId);
        }
        return termination;
    }


}
